package commons.base.elasticsearch;

import org.elasticsearch.action.bulk.BulkRequestBuilder;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequestBuilder;
import org.elasticsearch.client.Client;
import org.elasticsearch.common.xcontent.XContentBuilder;

public class BulkOp {

	private Client client;
	private BulkRequestBuilder bulkRequestBuilder;
	private int size;
	private int maxSize;
	
	public BulkOp(Client client, int maxSize){
		this.client = client;
		this.maxSize = maxSize;
		bulkRequestBuilder = client.prepareBulk();
	}
	
	public BulkOp update(String index, String type, String id, XContentBuilder sourceBuilder){
		return update(client.prepareIndex(index, type).setId(id).setSource(sourceBuilder));
	}
	
	public BulkOp update(IndexRequestBuilder request){
		bulkRequestBuilder.add(request);
		size ++;
		
		checkFull();
		return this;
	}
	
	private void checkFull(){
		if(isFull()){
			execute();
			
			size = 0;
			bulkRequestBuilder = client.prepareBulk();
		}
	}
	
	public boolean isFull(){
		return size >= maxSize;
	}
	
	public boolean isEmpty(){
		return size <= 0;
	}
	
	public BulkResponse execute(){
		return bulkRequestBuilder.execute().actionGet();
	}
}
